package com.ruoyi.business.taskListener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.business.domain.FilePerson;
import com.ruoyi.business.domain.vo.FileTransferOutVo;
import com.ruoyi.business.mapper.FilePersonMapper;
import com.ruoyi.business.service.impl.FileTransferOutServiceImpl;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;

/**
 * 厂内动过流程监听器，根据流程变动修改业务实体
 *
 * @author XXYD
 */
@Slf4j
public class FileTransferOutListener implements ActivitiEventListener, ExecutionListener, TaskListener {
    /**
     * 事件监听器
     *
     * @param event the event
     */
    @Override
    public void onEvent(ActivitiEvent event) {
        log.info("监听到事件：{}", event.getType());
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

    /**
     * 执行监听器
     *
     */

    @Override
    public void notify(DelegateExecution execution) {
        //监听到流程就输，修改业务实体状态
        String processInstanceBusinessKey = execution.getProcessInstanceBusinessKey();
        FileTransferOutServiceImpl bean = SpringUtils.getBean(FileTransferOutServiceImpl.class);
        FileTransferOutVo fileTransferOutVo = bean.queryById(Long.valueOf(processInstanceBusinessKey));
        FilePersonMapper personMapper =   SpringUtils.getBean(FilePersonMapper.class);
        if (fileTransferOutVo.getType().equals("1")){
            FilePerson filePerson = personMapper.selectOne(new LambdaQueryWrapper<>(FilePerson.class)
                .eq(FilePerson::getId, fileTransferOutVo.getGoToPerson()));
            if (filePerson != null){
                filePerson.setOrgid(Long.valueOf(fileTransferOutVo.getGoToUnits()));
                personMapper.updateById(filePerson);
            }
        }
    }

    /**
     * 任务监听器
     *
     * @param delegateTask
     */
    @Override
    public void notify(DelegateTask delegateTask) {
        log.info("监听到任务：{}", delegateTask.getEventName());
        // 当前版本中，任务监听器不需要执行特定逻辑
        // 仅作为Activiti流程引擎要求的接口实现而存在
        // 后续如有需要处理任务相关逻辑，可在此处添加实现
    }
}
